package activate.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

public class MyFile {

	public static byte[] inputStreamToBytes(InputStream in) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = in.read(buff, 0, 100)) > 0) {
			baos.write(buff, 0, rc);
		}
		return baos.toByteArray();
	}

	public static void bytesToFile(byte[] bytes, String target) throws Exception {
		File outFile = new File(target);
		if (outFile.exists() && outFile.isFile()) {
			outFile.delete();
		}
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile));
		bos.write(bytes);
		bos.close();
	}

	public static void inputStreamToFile(InputStream in, String target) throws Exception {
		bytesToFile(inputStreamToBytes(in), target);
	}

	public static void copy(String source, String target) throws Exception {

		File inFile = new File(source);
		File outFile = new File(target);
		if (outFile.exists() && outFile.isFile()) {
			outFile.delete();
		}
		FileInputStream fis = new FileInputStream(inFile);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int n;
		while ((n = fis.read(b)) != -1) {
			baos.write(b, 0, n);
		}
		fis.close();
		baos.close();
		byte[] fileBytes = baos.toByteArray();
		BufferedOutputStream bos = null;
		bos = new BufferedOutputStream(new FileOutputStream(outFile));
		bos.write(fileBytes);
		bos.close();

	}

}
